package com.ivncorp.evnproject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBar.LayoutParams;
import android.support.v7.app.ActionBarActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.ivncorp.evnproject.adapter.ImageGalleryAdapter;
import com.ivncorp.evnproject.chart.SalesStackedBarChartTram;
import com.ivncorp.evnproject.data.DaoMaster;
import com.ivncorp.evnproject.data.DaoMaster.DevOpenHelper;
import com.ivncorp.evnproject.data.DaoSession;
import com.ivncorp.evnproject.data.TramDao;
import com.ivncorp.evnproject.helpers.InternetConnectionChecker;
import com.ivncorp.evnproject.helpers.Variables;
import com.ivncorp.evnproject.model.ObjectTram;
import com.ivncorp.evnproject.upload.MyServiceTram;
import com.ivncorp.evnproject.upload.MyServiceTram.LocalBinder;
import com.ivncorp.evnproject.upload.UploadErrorCode;
import com.ivncorp.evnproject.upload.UploadFilesCompleteListener;

public class ActivityGalleryTram extends ActionBarActivity implements
		OnClickListener {

	ArrayList<ObjectTram> imageUrls;
	ArrayList<ObjectTram> currentList = new ArrayList<ObjectTram>();
	ImageGalleryAdapter adapter;
	// private Menu menu;

	GridView gridview;

	private int selectedPosition = -1;
	private boolean uploadding = false;
	private int idUploadding = -1;
	private Broasdcast broasdcast;
	private LinearLayout layoutFunction;
	private LinearLayout layoutSearch;
	private EditText txtSearch;
	// for DAO
	private SQLiteDatabase dbDao;
	private DaoSession daoSession;
	private DaoMaster daoMaster;
	private TramDao tramDao;
	private Cursor cursor;

	@SuppressLint("InflateParams")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_gallery);

		// set actionbar
		ActionBar actionBar = getSupportActionBar();
		actionBar.setDisplayShowHomeEnabled(true);
		actionBar.setDisplayShowCustomEnabled(true);
		actionBar.setDisplayShowTitleEnabled(false);
		actionBar.setDisplayUseLogoEnabled(false);
		actionBar.setIcon(R.drawable.ic_launcher);

		LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View actionbarView = inflater.inflate(R.layout.actionbar_gallery_tram,
				null);
		@SuppressWarnings("deprecation")
		LayoutParams layoutActionbar = new LayoutParams(
				LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);

		layoutFunction = (LinearLayout) actionbarView
				.findViewById(R.id.galleryFunction);
		layoutSearch = (LinearLayout) actionbarView
				.findViewById(R.id.gallerySearch);
		txtSearch = (EditText) actionbarView
				.findViewById(R.id.txtGallerySearch);
		actionBar.setCustomView(actionbarView, layoutActionbar);

		// action search
		txtSearch.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				currentList.clear();
				currentList.addAll(search(txtSearch.getText().toString()));
				Variables.currentListObjectTable = currentList;
				adapter.notifyDataSetChanged();
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}
		});

		broasdcast = new Broasdcast();
		registerReceiver(broasdcast, new IntentFilter("uploadding"));

		getActionBar().setDisplayShowTitleEnabled(false);
		imageUrls = new ArrayList<ObjectTram>();
		adapter = new ImageGalleryAdapter(ActivityGalleryTram.this, currentList);

		gridview = (GridView) findViewById(R.id.galleryGridView);
		gridview.setAdapter(adapter);
		gridview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {

				final Intent intent = new Intent(ActivityGalleryTram.this,
						ActivityGalleryViewItemTram.class);
				intent.putExtra("input", "object");
				intent.putExtra("object", currentList.get(position));

				new Thread(new Runnable() {

					@Override
					public void run() {

						startActivity(intent);
					}
				}).start();
			}

		});

		gridview.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id) {
				selectedPosition = position;

				return false;
			}
		});

		registerForContextMenu(gridview);
		progressDialog = new ProgressDialog(ActivityGalleryTram.this);
		progressDialog.setMessage("Loading...");
		progressDialog.setIndeterminate(false);
		progressDialog.setCancelable(false);

		getActionBar().setDisplayShowHomeEnabled(true);
		getActionBar().setDisplayHomeAsUpEnabled(true);

	}

	@Override
	public void onResume() {
		DevOpenHelper helper = new DaoMaster.DevOpenHelper(
				getApplicationContext(), Variables.NAME_DATABSE, null);
		dbDao = helper.getWritableDatabase();
		daoMaster = new DaoMaster(dbDao);
		daoSession = daoMaster.newSession();
		tramDao = daoSession.getTramDao();
		new LoadImageAsynTask().execute();
		super.onResume();

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			break;
		default:
			break;
		}

		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		menu.setHeaderTitle(R.string.chon_chuc_nang);
		menu.add(0, v.getId(), 0, R.string.tai_len);
		menu.add(0, v.getId(), 0, R.string.chinh_sua);
		menu.add(0, v.getId(), 0, R.string.xoa);
	}

	@Override
	protected void onStart() {
		super.onStart();
		// bind to service
		Intent i = new Intent(this, MyServiceTram.class);
		bindService(i, mConnection, Context.BIND_AUTO_CREATE);
	}

	@Override
	protected void onStop() {
		super.onStop();
		// Unbind from the service
		if (mBound) {
			unbindService(mConnection);
			mBound = false;
		}
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		String title = item.getTitle().toString();
		if (title.equals(getApplicationContext().getString(R.string.tai_len))) {
			if (InternetConnectionChecker
					.isNetworkConnected(ActivityGalleryTram.this)) {
				ObjectTram objectTable = new ObjectTram();
				objectTable = currentList.get(selectedPosition);
				if (objectTable.getUploaded() == 1) {
					Toast.makeText(getApplicationContext(),
							R.string.doi_tuong_nay_da_dc_tai_len_,
							Toast.LENGTH_SHORT).show();
				} else {
					if (!uploadding) {
						if (idUploadding == objectTable.getId_object()) {
							Toast.makeText(
									getApplicationContext(),
									R.string.doi_tuong_nay_dang_dc_tai_len_vui_long_tai_len_doi_tuong_khac_,
									Toast.LENGTH_SHORT).show();
						} else {
							createUploadtable(objectTable);
							uploadding = true;
						}
					} else {
						Toast.makeText(getApplicationContext(),
								R.string.dang_tai_len_khong_the_tai_them_,
								Toast.LENGTH_SHORT).show();
					}
				}
			} else {
				Toast.makeText(
						getApplicationContext(),
						R.string.khong_co_ket_noi_voi_internet_vui_long_ket_noi_internet_,
						Toast.LENGTH_SHORT).show();
			}

		} else if (title.equals(getApplicationContext().getString(
				R.string.chinh_sua))) {

			Intent intent = new Intent(ActivityGalleryTram.this,
					ActivityCreateTram.class);
			intent.putExtra("object", currentList.get(selectedPosition));

			startActivityForResult(intent, 1);

		} else if (title
				.equals(getApplicationContext().getString(R.string.xoa))) {
			new AlertDialog.Builder(ActivityGalleryTram.this)
					.setTitle(R.string.xoa)
					.setMessage(R.string.ban_co_muon_xoa_doi_tuong_nay_khong_)
					.setPositiveButton(R.string.co,
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									try {

										ObjectTram table = currentList
												.get(selectedPosition);
										tramDao.deleteByKey(table
												.getId_object());
										File file1 = new File(table
												.getImage_1());
										file1.delete();
										File file2 = new File(table
												.getImage_2());
										file2.delete();
										File file3 = new File(table
												.getImage_3());
										file3.delete();
										File file4 = new File(table
												.getImage_4());
										file4.delete();
										File file5 = new File(table
												.getImage_5());
										file5.delete();
										currentList.remove(selectedPosition);
										deleteObject(table.getCode());
										adapter.notifyDataSetChanged();
										Variables.currentListObjectTable = currentList;
										Toast.makeText(
												ActivityGalleryTram.this,
												R.string.xoa_thanh_cong_,
												Toast.LENGTH_SHORT).show();
									} catch (Exception e) {
										Toast.makeText(
												ActivityGalleryTram.this,
												R.string.xoa_that_bai_,
												Toast.LENGTH_SHORT).show();
									}

								}
							})
					.setNegativeButton(R.string.khong,
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									dialog.dismiss();
								}
							}).show();

		} else {
			return false;
		}
		return true;
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		adapter.clearData();
		new LoadImageAsynTask().execute();
		super.onActivityResult(requestCode, resultCode, data);
	}

	private ProgressDialog progressDialog;

	class LoadImageAsynTask extends AsyncTask<Integer, ObjectTram, Void> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progressDialog.show();
		}

		@Override
		protected Void doInBackground(Integer... params) {

			ArrayList<ObjectTram> list_object = new ArrayList<ObjectTram>();
			cursor = dbDao.query(tramDao.getTablename(),
					tramDao.getAllColumns(), null, null, null, null, null);
			if (cursor != null) {
				while (cursor.moveToNext()) {
					ObjectTram tram = new ObjectTram(cursor.getLong(0),
							(byte) cursor.getInt(1), cursor.getString(2),
							cursor.getString(3), cursor.getString(4),
							cursor.getString(5), cursor.getString(6),
							cursor.getString(7), cursor.getString(8),
							cursor.getString(9), (int) cursor.getLong(10));
					list_object.add(tram);
				}
				cursor.close();
			}

			if (list_object.size() > 0) {
				imageUrls.clear();
				imageUrls.addAll(list_object);
			}

			return null;
		}

		@Override
		protected void onPostExecute(Void params) {
			currentList.clear();
			currentList.addAll(imageUrls);
			Variables.currentListObjectTable = currentList;
			adapter.notifyDataSetChanged();
			progressDialog.dismiss();
		}

	}

	/*----------------upload-----------------*/
	private void createUploadtable(ObjectTram objectTable) {
		List<ObjectTram> input = new ArrayList<ObjectTram>();
		input.add(objectTable);

		if (input.size() > 0) {
			mService.uploadFiles(input);
			mService.setUploadFilesCompleteListener(completeListener);
		}

	}

	boolean mBound;
	MyServiceTram mService;
	private ServiceConnection mConnection = new ServiceConnection() {

		@Override
		public void onServiceDisconnected(ComponentName name) {
			mBound = false;
		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// Bound to MyService.
			LocalBinder binder = (LocalBinder) service;
			mService = binder.getService();
			mBound = true;
		}
	};

	UploadFilesCompleteListener completeListener = new UploadFilesCompleteListener() {

		@Override
		public void onCompleted(UploadErrorCode errorCode) {

			ObjectTram objectTable = new ObjectTram();
			objectTable = currentList.get(selectedPosition);
			objectTable.setUploaded((byte) 1);
			adapter.notifyDataSetChanged();
			tramDao.update(objectTable);

			Toast.makeText(getApplicationContext(),
					R.string.tai_len_thanh_cong_, Toast.LENGTH_SHORT).show();

		}
	};

	private class Broasdcast extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals("uploadding")) {
				String status = intent.getStringExtra("status");
				int id = intent.getIntExtra("id", -1);
				if (status.equals("uploadding")) {
					idUploadding = id;
				} else if (status.equals("uploadComplete")) {
					for (ObjectTram table : currentList) {
						if (table.getId_object() == id) {

							table.setUploaded((byte) 1);
							adapter.notifyDataSetChanged();
							tramDao.update(table);
							break;
						}
					}
					idUploadding = -1;
				}

			}
		}

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(broasdcast);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnGallerySearch:
			layoutSearch.setVisibility(View.VISIBLE);
			layoutFunction.setVisibility(View.GONE);
			break;
		case R.id.btnGalleryMaps:
			Intent intent = new Intent(this, ActivityMapOffline.class);
			intent.putExtra("input", "type");
			startActivity(intent);
			break;
		case R.id.btnGalleryCancel:
			layoutFunction.setVisibility(View.VISIBLE);
			layoutSearch.setVisibility(View.GONE);
			break;
		case R.id.btnGalleryCreate:
			Intent intent2 = new Intent(this, ActivityCreateTram.class);
			startActivityForResult(intent2, 1);
			break;
		case R.id.btnGalleryStatistics:
			startActivity(new Intent(
					new SalesStackedBarChartTram()
							.execute(getApplicationContext())));
			break;
		default:
			break;
		}

	}

	@SuppressLint("DefaultLocale")
	private ArrayList<ObjectTram> search(String key) {
		ArrayList<ObjectTram> result = new ArrayList<ObjectTram>();
		for (ObjectTram objectTable : imageUrls) {
			if (objectTable.getName().toLowerCase().contains(key.toLowerCase())
					|| objectTable.getCode().toLowerCase()
							.contains(key.toLowerCase())) {
				result.add(objectTable);
			}
		}
		return result;
	}

	private void deleteObject(String key) {
		for (int i = 0; i < imageUrls.size(); i++) {
			if (imageUrls.get(i).getCode().equals(key)) {
				imageUrls.remove(i);
				break;
			}
		}
	}
}